/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.upn.sigemfi.seg.bc;

import edu.upn.sigemfi.seg.be.Persona;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author Programador
 */
public class PersonaDelegate {

    private PersonaFacadeLocal local;

    public PersonaDelegate() {
        local = lookupPersonaFacade();
    }

    public void crear(Persona persona) throws Exception {
        try {
            local.create(persona);
        } catch (Exception e) {
            local = lookupPersonaFacade();
            throw new Exception("Crear Persona. " + e.getMessage(), e);
        }
    }

    public void editar(Persona persona) throws Exception {
        try {
            local.edit(persona);
        } catch (Exception e) {
            local = lookupPersonaFacade();
            throw new Exception("Editar Persona. " + e.getMessage(), e);
        }
    }

    public void eliminar(Persona persona) throws Exception {
        try {
            local.remove(persona);
        } catch (Exception e) {
            local = lookupPersonaFacade();
            throw new Exception("Eliminar Persona. " + e.getMessage(), e);
        }
    }

    public Persona buscar(Long codigo) throws Exception {
        try {
            return local.find(codigo);
        } catch (Exception e) {
            local = lookupPersonaFacade();
            throw new Exception("Buscar Persona. " + e.getMessage(), e);
        }
    }

    public List<Persona> listar() throws Exception {
        try {
            return local.findAll();
        } catch (Exception e) {
            local = lookupPersonaFacade();
            throw new Exception("Listar Agencias. " + e.getMessage(), e);
        }
    }

    private PersonaFacadeLocal lookupPersonaFacade() {
        try {
            Context c = new InitialContext();
            return (PersonaFacadeLocal) c.lookup("java:comp/env/PersonaFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
}
